import { Context } from 'egg';
import * as jwt from 'jsonwebtoken';
module.exports = (option) => {
  return async (ctx: Context, next) => {
    console.log(ctx.request.header['authorization']);
    if (ctx.request.header['authorization']) {
      const token = ctx.request.headers['authorization'];
      try {
        jwt.verify(token, ctx.app.config.jwtSecret);
      } catch (error) {
        if (error.name === 'TokenExpiredError') {
          ctx.fail('登录已过期', 401)
          // ctx.throwBizError({ status: 401, code: 401, message: '登录已过期', log: false });
          return;
        } else {
          ctx.fail('错误的token', 403)
          return;
        }
      }
      await next(option);
    } else {
      ctx.fail('您未登录，请登录后再试', 403)
      return;
    }
  };
};
